
<template>
  
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品ID" prop="drugId">
        <el-input
          v-model="queryParams.drugId"
          placeholder="请输入药品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产批号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入生产批号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产日期" prop="productionDate">
        <el-date-picker clearable
          v-model="queryParams.productionDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择生产日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="有效期至" prop="expiryDate">
        <el-date-picker clearable
          v-model="queryParams.expiryDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择有效期至">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商ID" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
     <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['inventory:inventory:add']"
        >新增</el-button>
      </el-col> 
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:inventory:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:inventory:remove']"
        >删除</el-button>
      </el-col> -->

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['inventory:inventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="批次ID" align="center" prop="inventoryId" />
      <el-table-column label="药品名称" align="center" prop="drugName" /> <!-- 新增列 -->
      <el-table-column label="药品ID" align="center" prop="drugId" v-if="false"/> <!-- 隐藏原始ID列 -->
      <el-table-column label="库存数量" align="center" prop="stockQuantity" />
      <el-table-column label="存放位置" align="center" prop="location" />
      <el-table-column label="生产批号" align="center" prop="batchNumber" />
      <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期至" align="center" prop="expiryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商ID" align="center" prop="supplier" />
      <el-table-column label="最后盘点时间" align="center" prop="lastCheck" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastCheck, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['inventory:inventory:edit']">查看</el-button>
          <el-button link type="primary" icon="List" @click="mingxi(scope.row)" >明细</el-button>

          <!-- 出库入库明细弹窗 -->
<el-dialog 
  v-model="detailVisible" 
  title="库存流转明细" 
  width="80%"
  append-to-body
>
  <el-tabs v-loading="detailLoading">
    <!-- 出库记录 -->
    <el-tab-pane label="出库记录">
      <el-table :data="outboundList" border height="400">
        <el-table-column label="出库单号" prop="outboundId" align="center" />
        <el-table-column label="药品名称" prop="drugName" align="center" />
        <el-table-column label="出库数量-" prop="stockQuantity" align="center" />
        <el-table-column label="出库方式" prop="usageDescription" align="center" />
        <el-table-column label="使用人员" prop="user" align="center" />
        <el-table-column label="出库时间" prop="outboundTime" align="center" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" prop="outboundAdmin" align="center" />
      </el-table>
      <!-- 出库分页（根据接口返回字段调整） -->
      <!-- <pagination 
        v-show="outboundTotal>0" 
        :total="outboundTotal"
        v-model:page="outboundQuery.pageNum"
        v-model:limit="outboundQuery.pageSize"
        @pagination="fetchOutbound"
      /> -->
    </el-tab-pane>

    <!-- 入库记录 -->
    <el-tab-pane label="入库记录">
      <el-table :data="storeList" border height="400">
        <el-table-column label="入库单号" prop="storeId" align="center" />
        <el-table-column label="药品名称" prop="drugName" align="center" />
        <el-table-column label="入库数量+" prop="stockQuantity" align="center" />
        <el-table-column label="存放地址" prop="location" align="center" />
        <el-table-column label="供应商" prop="supplier" align="center" />
        <el-table-column label="生产日期" prop="productionDate" align="center" />
        <el-table-column label="有效期" prop="expiryDate" align="center" />

        
        <el-table-column label="入库时间" prop="storeDate" align="center" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.storeDate, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" prop="storeAdmin" align="center" />
      </el-table>
      <!-- 入库分页 -->
      <!-- <pagination 
        v-show="storeTotal>0" 
        :total="storeTotal"
        v-model:page="storeQuery.pageNum"
        v-model:limit="storeQuery.pageSize"
        @pagination="fetchStore"
      /> -->
    </el-tab-pane>
  </el-tabs>
  
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="detailVisible = false">关 闭</el-button>
    </div>
  </template>
</el-dialog>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品库存对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="inventoryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品名称" prop="drugId">
          <el-autocomplete
            v-model="drugNameQuery"
            :fetch-suggestions="searchDrugs"
            placeholder="请输入药品名称"
            value-key="drugName"
            @select="handleDrugSelect"
            clearable
          >
            <template #default="{ item }">
              <div>{{ item.drugName }} - 单位:({{ item.unit }}) -规格:({{ item.spec }})</div>
            </template>
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入库存数量,新增默认入库" />
        </el-form-item>
        <el-form-item label="存放位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入存放位置" />
        </el-form-item>
        <el-form-item label="生产批号" prop="batchNumber">
          <el-input v-model="form.batchNumber" placeholder="请输入生产批号" />
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker clearable
            v-model="form.productionDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期至" prop="expiryDate">
          <el-date-picker clearable
            v-model="form.expiryDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择有效期至">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商ID" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商ID" />
        </el-form-item>
        <el-form-item label="最后盘点时间" prop="lastCheck">
          <el-date-picker clearable
            v-model="form.lastCheck"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择最后盘点时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Inventory">
import { listInventory, getInventory, delInventory, addInventory, updateInventory } from "@/api/inventory/inventory";
import { listDrugs } from "@/api/drugs/drugs"; // 新增药品接口引用
import { listOutbound } from "@/api/outbound/outbound";
import { listStore } from "@/api/store/store";



const { proxy } = getCurrentInstance();
const drugNameQuery = ref('');
const inventoryList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailVisible = ref(false);
const outboundList = ref([]);
const storeList = ref([]);
const detailLoading = ref(false);






const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    drugId: null,
    batchNumber: null,
    productionDate: null,
    expiryDate: null,
    supplier: null,
  },
  rules: {
    drugId: [
      { required: true, message: "药品ID不能为空", trigger: "blur" }
    ],
    stockQuantity: [
      { required: true, message: "库存数量不能为空", trigger: "blur" }
    ],
    batchNumber: [
      { required: true, message: "生产批号不能为空", trigger: "blur" }
    ],
    productionDate: [
      { required: true, message: "生产日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 药品搜索方法 */
const searchDrugs = async (queryString, cb) => {
  if (!queryString) {
    cb([]);
    return;
  }
  try {
    const res = await listDrugs({
      pageNum: 1,
      pageSize: 10,
      drugName: queryString
    });
    cb(res.rows);
  } catch {
    cb([]);
  }
};
/** 药品选择处理 */
const handleDrugSelect = (item) => {
  form.value.drugId = item.drugId;
  // 如果需要自动填充单位可以取消注释
  // form.value.unit = item.unit;
};






/** 查询药品库存列表 */
function getList() {
  loading.value = true;
  listInventory(queryParams.value).then(response => {
    inventoryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    inventoryId: null,
    drugId: null,
    stockQuantity: null,
    location: null,
    batchNumber: null,
    productionDate: null,
    expiryDate: null,
    supplier: null,
    lastCheck: null
  };
  drugNameQuery.value = '';
  proxy.resetForm("inventoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.inventoryId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药品库存";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _inventoryId = row.inventoryId || ids.value;
  getInventory(_inventoryId).then(response => {
    form.value = response.data;
    // 根据ID查询药品信息回显名称
    listDrugs({ drugId: form.value.drugId }).then(res => {
      if (res.rows.length > 0) {
        drugNameQuery.value = res.rows[0].drugName;
      }
    });
    open.value = true;
    title.value = "修改药品库存";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["inventoryRef"].validate(valid => {
    if (valid) {
      if (form.value.inventoryId != null) {
        updateInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _inventoryIds = row.inventoryId || ids.value;
  proxy.$modal.confirm('是否确认删除药品库存编号为"' + _inventoryIds + '"的数据项？').then(function() {
    return delInventory(_inventoryIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


/** 查看明细 */
async function mingxi(row) {
  detailLoading.value = true;
  
  try {
    // 并行查询出库和入库记录
    const [outboundRes, storeRes] = await Promise.all([
      listOutbound({ 
        inventoryId: row.inventoryId, // 根据批次号关联查询
      }),
      listStore({
        inventoryId: row.inventoryId,
      })
    ]);
    outboundList.value = outboundRes.rows;
    storeList.value = storeRes.rows;
    detailVisible.value = true;
  } catch (err) {
    proxy.$modal.msgError("数据加载失败");
  } finally {
    detailLoading.value = false;
  }
}





/** 导出按钮操作 */
function handleExport() {
  proxy.download('inventory/inventory/export', {
    ...queryParams.value
  }, `inventory_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped lang="scss">
/* 调整表格高度 */
.el-table--scrollable-y .el-table__body-wrapper {
  max-height: 60vh !important;
}

/* 标签页样式 */
.el-tabs__content {
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
</style>